import os
from pathlib import Path
from django.conf import settings
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-a@44g1%^_q^-g9f@$a3s^q=8f5vrf2-niunuhc2yi5-)n&#p$9'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['chefshub.cn', 'www.chefshub.cn', 'localhost','127.0.0.1']
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')


MEDIA_URL = '/media/'
STATIC_URL = '/static/'
MEDIA_ROOT = '/var/www/django_project/djangocookproj/media'
STATIC_ROOT = '/var/www/django_project/djangocookproj/static'
#MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 默认头像URL
DEFAULT_AVATAR_URL = '/static/default_avatar.png'

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    "https://您的微信云开发域名.com", # 微信云开发默认域名
    "https://servicewechat.com",     # 微信小程序通用域名
    "https://chefshub.cn",
    "http://127.0.0.1:8000",
    "http://localhost:8000"
]
CORS_ALLOW_HEADERS = [
    'authorization',
    'content-type',
    'x-requested-with',
]
CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]
# ASGI_APPLICATION = 'config.asgi.application'
# CHANNEL_LAYERS = {
#     "default": {
#         "BACKEND": "channels_redis.core.RedisChannelLayer",
#         "CONFIG": {"hosts": [("127.0.0.1", 6379)]},
#     }
# }

WECHAT_CONFIG = {
    'consumer': {
        'appid': os.environ['WECHAT_CONSUMER_APPID'], 
        'secret': os.environ['WECHAT_CONSUMER_SECRET'],
        'mchid': os.environ['WECHAT_MCHID'],  # 商户号
        'private_key': os.environ['WECHAT_PRIVATE_KEY'],  # 商户私钥（PEM格式）
        'api_v3_key': os.environ['WECHAT_API_V3_KEY'],   
        'cert_serial_no': os.environ['WECHAT_MCHID_SERIO'],
        'notify_url': 'https://chefshub.cn/api/orders/pay/notify/',  # 支付结果通知地址
        'encoding_aes_key': os.environ['WECHAT_CONSUMER_ENCODING_AES_KEY'],
    },
    'provider': {
        'appid': os.environ.get('WECHAT_PROVIDER_APPID', ''),
        'secret': os.environ.get('WECHAT_PROVIDER_SECRET', ''),
        'encoding_aes_key': os.environ['WECHAT_PROVIDER_ENCODING_AES_KEY'],
        'WECHAT_PROVIDER_ORDER_TEMPLATE_ID': os.environ['WECHAT_PROVIDER_ORDER_TEMPLATE_ID']
    }
}

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'corsheaders',
    'django_filters',
    'rest_framework',
    'rest_framework_simplejwt',
    'rest_framework.authtoken',
    'apps.accounts',
    'apps.chefs.apps.ChefsConfig',
    'apps.orders',
    'apps.payments',
    'apps.reviews',
    'apps.address.apps.AddressConfig',
    'apps.favorites.apps.FavoritesConfig',
    'apps.history',
    'apps.system',
    'apps.upload.apps.UploadConfig',
    'apps.menu',
    'apps.notic',
    'apps.dishes',
    'apps.schedules',
    'channels'

]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
    'DEFAULT_THROTTLE_RATES': {
        'address': '10/minute'  # 限流配置
    },
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10

}

# JWT 配置
from datetime import timedelta

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': settings.SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'JWK_URL': None,
    'LEEWAY': 0,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'apps.address.middleware.AddressOwnershipMiddleware',
]

ROOT_URLCONF = 'config.urls'

CACHES = {
    'address': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',  # 本地内存缓存'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/2',
        'TIMEOUT': 300  # 5分钟
    },
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake/1',
        # 'OPTIONS': {
        #     'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        # }
    }
}

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_cookdb',       # 数据库名
        'USER': 'django_cookdb',             # 用户名
        'PASSWORD': 'Django_cookdb1234!',         # 密码
        'HOST': 'localhost',                 # 主机
        'PORT': '3306',                      # 端口
        'OPTIONS': {
            'charset': 'utf8mb4',            # 支持emoji
            #'use_index_merge': False,
        },
         'INDEX_HINTS': {
            'address': ['province', 'city'],  # 显式指定索引
        },
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/

AUTH_USER_MODEL = 'accounts.User'
ADMIN_SITE_HEADER = "CookProj 管理系统"
ADMIN_SITE_TITLE = "CookProj 管理后台"

fieldsets = (
    (None, {'fields': ('openid',)}),  # 移除password
    ...
)

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    # 其他备用算法...
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True  # 启用时区支持

USE_I18N = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/

# STATIC_URL = 'https://chefshub.cn/static/'
# #STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# STATIC_ROOT = '/var/www/django_project/djangocookproj/static'
# MEDIA_URL = 'https://chefshub.cn/media/'
# MEDIA_ROOT = '/var/www/django_project/djangocookproj/media'

# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',  # 输出到控制台
        },
    },
    'loggers': {
        '': {  # 所有日志
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}